package servlet;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Random;

@WebServlet("/ip")
public class RandomIpSerLet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //亂碼處理
        resp.setContentType("text/html;charset=utf-8");

        count(req,resp);
    }

    //文件讀入統計出現次數
    public void count(HttpServletRequest req, HttpServletResponse resp){
        BufferedReader br = null;
        //創建Map集合
        HashMap<String, Integer> map = new HashMap<>();
        //讀入文件
        try {
            InputStream resource = getClass().getResourceAsStream("/id.txt");
            br = new BufferedReader(new InputStreamReader(resource,"utf-8"));
            String line = null;
            while ((line = br.readLine())!=null){
                if(map.containsKey(line)){
                    Integer val = map.get(line);
                    val++;
                    map.put(line,val);
                }else {
                    map.put(line,1);
                }



            }
            //讀取，然後存入JSON中
            String s1 = JSON.toJSONString(map);
            resp.getWriter().print(s1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //關流
        try {
            if (br!=null){
                br.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }



}
